package aviator;

import cn.hutool.Hutool;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program JavaBase
 * @description: 测试
 * @author: zhanglu
 * @create: 2020-11-10 16:42:00
 */
@Slf4j
public class ParameterAnalysisTest01 {

    @Test
    public void test01(){
        Info info = new Info();
        info.setName("张三").setAge(1).setBirth(new Date());
        Expression compile =  AviatorEvaluator.getInstance().compile("test01", "name+(age==1?'先生':'女士') + '您好！生日：'+birth+'。'" +
                "+date_to_string(birth,'yyyy-MM-dd HH:mm:ss')", true);
        Object execute = compile.execute(JSONUtil.parseObj(info));
        log.info(execute.toString());
    }

    @Test
    public void test02(){
        List<InfoItem> infoItemList = new ArrayList<>();
        infoItemList.add(new InfoItem().setP1("item1-p1").setP2("item1-p2").setP3("item1-p3"));
        infoItemList.add(new InfoItem().setP1("item2-p1").setP2("item2-p2").setP3("item2-p3"));
        Info info = new Info();
        info.setName("张三").setAge(1).setBirth(new Date());
        info.setItemList(infoItemList);
        Expression compile = AviatorEvaluator.compile("name+(age==1?'先生':'女士') + '您好！生日：'+birth+'。'+#itemList[0].p1");
//                "\t(#itemList == nil ? '' : '明细：'+#itemList[0].p1+'-'+#itemList[1].p1)");
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(info);
        Object execute = compile.execute(jsonObject);
        log.info(execute.toString());
        info.setName("张三").setAge(2).setBirth(new Date());
        info.setItemList(infoItemList);
        execute = compile.execute(JSONUtil.parseObj(info));
        log.info(execute.toString());
    }

    /**
     * 解析json，消息模版
     */
    @Test
    public void test03(){
        StringBuilder expressionBuilder = new StringBuilder();
        String responseStr = "{\"code\":1,\"data\":{\"name\":\"张三\",\"age\":1,\"phone\":\"17356524108\",\"idCard\":\"340302199701080014\",\"ticket\":{\"trainNumber\":\"G1703\",\"startPoint\":\"南京\",\"endPoint\":\"蚌埠\",\"startDate\":\"2020-11-11 09:00:00\",\"endDate\":\"2020-11-11 09:45:00\"},\"history\":[{\"trainNumber\":\"G1701\",\"startPoint\":\"蚌埠\",\"endPoint\":\"合肥\",\"startDate\":\"2020-11-09 14:30:00\",\"endDate\":\"2020-11-09 15:25:00\"},{\"trainNumber\":\"G1702\",\"startPoint\":\"合肥\",\"endPoint\":\"南京\",\"startDate\":\"2020-11-09 22:30:00\",\"endDate\":\"2020-11-09 23:15:00\"}]}}";
        expressionBuilder.append("let p1 = data.name + (data.age == 1 ? '先生' : '女士');\n" +
                "    let p2 = '';\n" +
                "    let hour = long(date_to_string(sysdate(),'HH'));\n" +
                "    if(6<=hour && hour<11){\n" +
                "    p2 = '，早上好。'\n" +
                "    }elsif(11<=hour && hour<14){\n" +
                "    p2 = '，中午好。'\n" +
                "    }elsif(14<=hour && hour<18){\n" +
                "    p2 = '，下午好。'\n" +
                "    }elsif(18<=hour && hour<24 || hour < 6){\n" +
                "    p2 = '，晚上好。'\n" +
                "    };\n" +
                "    let p3 = '这里是12306网站的提示。';\n" +
                "    let p4 = '您已经成功购买' + data.ticket.trainNumber + '车次的火车票.';\n" +
                "    let p5 = '您的列车将于' + data.ticket.startDate + '发车.';\n" +
                "    return p1 + p2 + p3 + p4 + p5;");
        String expressionStr = expressionBuilder.toString();
        log.info(expressionStr);
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        Expression expression = AviatorEvaluator.getInstance().compile("test03", expressionStr, true);
        Object execute = expression.execute(jsonObject);
        List<String> variableFullNames = expression.getVariableFullNames();

        if(execute instanceof String){
            log.info(execute.toString());
        }
    }

    @Test
    public void test031(){
        StringBuilder expressionBuilder = new StringBuilder();
        String responseStr = "{\"code\":1,\"data\":{\"name\":\"张三\",\"age\":1,\"phone\":\"17356524108\",\"idCard\":\"340302199701080014\",\"ticket\":{\"trainNumber\":\"G1703\",\"startPoint\":\"南京\",\"endPoint\":\"蚌埠\",\"startDate\":\"2020-11-11 09:00:00\",\"endDate\":\"2020-11-11 09:45:00\"},\"history\":[{\"trainNumber\":\"G1701\",\"startPoint\":\"蚌埠\",\"endPoint\":\"合肥\",\"startDate\":\"2020-11-09 14:30:00\",\"endDate\":\"2020-11-09 15:25:00\"},{\"trainNumber\":\"G1702\",\"startPoint\":\"合肥\",\"endPoint\":\"南京\",\"startDate\":\"2020-11-09 22:30:00\",\"endDate\":\"2020-11-09 23:15:00\"}]}}";
        String expressionStr = "''+(data.age==1?'先生':'女士')+'这里是12306网站的提示。您已经成功购买'+data.ticket.trainNumber+'车次的火车票。您的列车将于'+data.ticket.startDate+'发车。'";
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        Expression expression = AviatorEvaluator.getInstance().compile("test031", expressionStr, true);
        Object execute = expression.execute(jsonObject);
        List<String> variableFullNames = expression.getVariableFullNames();
        if(execute instanceof String){
            log.info(execute.toString());
        }
    }

    @Test
    public void test04() throws Exception {
//        //http://blog.showlu.top/blog/article/list?sort=sa.update_time&order=desc&page=1&limit=15
//        String expressionStr = "let hutool = require('HttpUtil');\n" +
//                "let request = hutool.createGet(\"http://blog.showlu.top/blog/article/list\");\n" +
//                "    request.form(\"sort\", \"sa.update_time\");\n" +
//                "    request.form(\"order\", \"desc\");\n" +
//                "    request.form(\"page\", 1);\n" +
//                "    request.form(\"limit\", 15);\n" +
//                "let response = request.execute();\n" +
//                "let res = response.body();";
//        AviatorEvaluatorInstance instance = AviatorEvaluator.getInstance();
//        instance.addModule(LuHttpUtils.class);
//        Expression expression = instance.compile("test04", expressionStr, true);
//        Object execute = expression.execute();
//        log.info(execute.toString());
        String body = HttpUtil.createGet("http://blog.showlu.top/blog/article/list")
                .form("sort", "sa.update_time")
                .form("order", "desc")
                .form("page", "1")
                .form("limit", "15")
                .execute().body();
        log.info(body);
    }

    @Test
    public void test05() throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("AviatorScript");

        File f = new File("/Users/zhanglu/Desktop/lu/workspace/dev_workspace/idea/学习/JavaBase/JavaBase/1.txt");
        // expose File object as variable to script
        engine.put("file", f);

        // evaluate a script string. The script accesses "file"
        // variable and calls method on it
        File[] files = f.listFiles();
        engine.eval("print(getParentFile(file))");
    }


    @Data
    @Accessors(chain = true)
    private static class Info{
        private String name;
        private Integer age;
        private Date birth;
        private List<InfoItem> itemList;
    }

    @Data
    @Accessors(chain = true)
    private static class InfoItem{
        private String p1;
        private String p2;
        private String p3;
    }

//    @Import(ns = "LuHttpUtils")
//    private class LuHttpUtils{
//
//        public String httpGet(String url, Map<String, Object> body){
//            String res = null;
//            Map<String, String> urlParams = HttpUtil.decodeParamMap(url, CharsetUtil.CHARSET_UTF_8);
//            urlParams.forEach((k, v) -> {
//
//            });
//            HttpRequest httpRequest = HttpRequest.get("http://blog.showlu.top/blog/article/list");
//            body.forEach((k, v) -> {
//                httpRequest.header(Header.CONTENT_TYPE, ContentType.JSON.getValue()).form("sort", "sa.update_time")
//                        .form("order", "desc")
//                        .form("page", 1)
//                        .form("limit", 15);
//            });
//            res = httpRequest.execute().body();
//            HttpRequest.get().setSSLProtocol();
//            return res;
//        }
//
//
//    }

}

